 //
//  PickupVC.m
//  ProjectforHDX
//
//  Created by yinda on 2018/6/7.
//  Copyright © 2018年 H.DX. All rights reserved.
//

#import "PickupVC.h"

#import "SearchBar.h" // 搜索框
#import "PickupHeadView.h" // 自定义headView
#import "ShipmentReportHeadView.h" // 自定义headView
#import "PickHeaderCell.h" // 自定义cell
#import "ShipmentReportCell.h" // 自定义cell

#import "AFNetworking.h"

#import "PlateModel.h"

#import "StockInquryDetailVC.h"

#import "StockPopVIewController.h"
#import "CunjianDetailVC.h"

#import "MainVC.h"
#import "PickupModel.h"
#import "OperationtipsView.h"
#import "CunquHomeVC.h"

typedef enum
{
    searchTypeFixpart=1,
    searchTypeFaultpart=2,
    searchTypeAll=3
}searchType;

@interface PickupVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,StockPopViewDelegate,UITextFieldDelegate> {
    /**
     *  cell数据 查询到的板件
     */
    NSMutableArray <PickupModel *>*dataArr;
    StockPopVIewController *_popView;
    BOOL hiden;
    UIButton *_typeBtn;
    UIButton *_storeNameBtn;
    //库存获取信息的数组
    NSMutableArray *stockArr;
    
    NSInteger teger;
    NSInteger tag;
    
    UIDatePicker *datePicker;
    UIToolbar *toolBar;
    
    UIButton *startBut;
    UIButton *endBut;
    
    BOOL isAll;  // 全选
    NSString *number; // 总共的数量
    
    NSInteger allCount;  /// 总共的数量
    NSMutableDictionary *coutmutableDic; // 存储操作过的板件数量
    NSString *pickserialnumber; // 取件流水号
    NSMutableArray *alreadySeletMuArr; // 存储已经选中过的按钮行
    
    OperationtipsView *feedabackView;
    UIView *bagview;
}

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *coverView;

@property (nonatomic, strong) PickupHeadView *headView;
@property (nonatomic, strong) ShipmentReportHeadView *SRHeadView;

//@property (nonatomic, assign) NSInteger *type;

@property (nonatomic, strong) UIView *searchHoldView;
/**
 *  网络请求参数
 */
@property (nonatomic, strong) NSMutableDictionary *postDict;
@property (nonatomic, strong) NSMutableDictionary *stockStrDict;
@property (nonatomic, strong) NSMutableArray *detailMutableArr; // 选择要取的板件数据
@property (nonatomic, strong) NSMutableArray *allMutableArr; // 可取的板件数据
@property (nonatomic ,strong)UIButton *selectedBt;  // 全选按钮
@property (nonatomic, strong) UIView *maskView;

@end

@implementation PickupVC{
    BOOL showPop;
}

static int type=1;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self horizontalscreensetting];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    stockArr = [NSMutableArray array];
    type = 1;
    isAll = NO;
    allCount = 0;
    self.detailMutableArr = [NSMutableArray new];
    coutmutableDic = [NSMutableDictionary new];
    alreadySeletMuArr = [NSMutableArray new];
    self.allMutableArr = [NSMutableArray new];
    self.postDict[@"type"] = [NSString stringWithFormat:@"%d",type];
    self.postDict[@"searchKey"]=@"";
    [self pickserialnumber];// 取件流水号
    [self InquiryInventory];
    [_stockStrDict setValue:[THMangerTool getKey] forKey:@"Key"];
    [self setupDatas];
    [self setupViews];
    
    
}

// 进入客服取件
-(void)kefuqujian:(UIButton *)sender{
    UIButton *bt = [self.view viewWithTag:20180802];
    if (sender.selected == NO) {
        [bt setTitle:[UtilCheck language:@"PickUpVC.surequjian"] forState:0];
        [Toolobject showAlterwithMessage:[UtilCheck language:@"PickUpVC.surequjiantishi"]];
    }
    else{
        [bt setTitle:[UtilCheck language:@"delivery.bottom5"] forState:UIControlStateNormal];
    }
    sender.selected = !sender.selected;
}

// 设置横屏
- (void)horizontalscreensetting{
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //允许转成横屏
    appDelegate.shouldChangeOrientation = YES;
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    
}

#pragma mark 数据初始化
- (NSMutableDictionary *)postDict
{
    if (!_postDict) {
        _postDict = [NSMutableDictionary dictionary];
    }
    return _postDict;
}
- (NSMutableDictionary *)stockStrDict
{
    if (!_stockStrDict) {
        _stockStrDict = [NSMutableDictionary dictionary];
    }
    return _stockStrDict;
}

- (void)setupDatas {
    dataArr = [NSMutableArray array];
}



#pragma mark 视图初始化
- (void)setupViews {
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];

    statusBarView.backgroundColor = SYSTEM_COLOR;

    [self.view addSubview:statusBarView];

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
//
    {
        UIView *backGroundView = [[UIView alloc]init];
        backGroundView.backgroundColor = SYSTEM_COLOR;
        [self.view addSubview:backGroundView];
        
        
        self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 44)];
        self.searchBar.delegate = self;
        self.searchBar.returnKeyType=UIReturnKeySearch;
        self.searchBar.backgroundColor = [UIColor blackColor];
        self.searchBar.placeholder = [UtilCheck language:@"setting.inputPlate"];
        [self.view addSubview:self.searchBar];
        
        UIImage* searchBarBg = [self GetImageWithColor:[UtilCheck hexStringToColor:@"E0E1E2" alpha:1.0] andHeight:32.0f];
        //设置背景图片`
        [_searchBar setBackgroundImage:searchBarBg];
        
        
        UIButton *backBtn = [[UIButton alloc]init];
        [backBtn setFrame:CGRectMake(0, 27, 30, 30)];
        [backBtn addTarget:self action:@selector(backView) forControlEvents:UIControlEventTouchUpInside];
//        backBtn.backgroundColor = [UtilCheck hexStringToColor:@"E0E1E2" alpha:1.0];
        [backBtn setImage:[UIImage imageNamed:@"base返回"] forState:UIControlStateNormal];
        [self.view addSubview:backBtn];
        
        UILabel *titellabel = [[UILabel alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-200)/2, 27, 200, 30)];
        titellabel.font = NavFontSize;
        titellabel.text = [self.type isEqualToString:@"1"]?[UtilCheck language:@"PickUpVC.qujian"] : [UtilCheck language:@"PickUpVC.qujianBad"];
        
        THUserInfoModel *model = [THMangerTool getAccountInfo];
        if ([model.userType isEqualToString:@"2"]||[model.userType isEqualToString:@"3"]) {
            UIButton *kefuqujianbt = [UIButton buttonWithType:0];
            kefuqujianbt.frame = CGRectMake(SCREEN_WIDTH - 80, 25, 70, 35);
            [kefuqujianbt setTitle:[UtilCheck language:@"PickUpVC.kefuqujian"] forState:0];
            kefuqujianbt.titleLabel.font = [UIFont systemFontOfSize:15];
            [kefuqujianbt addTarget:self action:@selector(kefuqujian:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:kefuqujianbt];
        }
        
        titellabel.textAlignment = NSTextAlignmentCenter;
        titellabel.textColor = [UIColor whiteColor];
        [self.view addSubview:titellabel];
        
        [backGroundView setFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 44)];
    }
    
    {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64+44, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 50 - 44) style:(UITableViewStylePlain)];
        
        // headView
        self.headView = [[PickupHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90)];
        //SRHeadView
//        self.SRHeadView = [[ShipmentReportHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90)];
        self.tableView.backgroundColor = [UtilCheck hexStringToColor:@"F5F7f8" alpha:1];
        if ([_stockStr isEqualToString:@"1"]) {
            [self.tableView registerClass:[ShipmentReportCell class] forCellReuseIdentifier:@"ShipmentReportCell"];
        }else {
            [self.tableView registerClass:[PickHeaderCell class] forCellReuseIdentifier:@"PickHeaderCell"];
        }
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        
        [self.view addSubview:self.tableView];
    }
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-50, SCREEN_WIDTH, 50)];
    // 灰色线
    UIImageView *grayImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0 , SCREEN_WIDTH, 1)];
    grayImageView.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:grayImageView];
    // 下一步按钮
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.tag = 20180802;
    nextButton.frame = CGRectMake(SCREEN_WIDTH - 120, 1, 120, 49);
    [nextButton setTitle:[UtilCheck language:@"delivery.bottom5"] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"确认存件"] forState:UIControlStateNormal];
    [bottomView addSubview:nextButton];
    // 合计件数
    UILabel *tallLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-230, 0, 110, 49)];
    tallLabel.tag = 1001;
    tallLabel.text  = [UtilCheck language:@"delivery.bottom8"];
    [bottomView addSubview:tallLabel];
    
    // 全选按钮
    self.selectedBt = [[RZCustomButtom alloc]init];
    [self.selectedBt setFrame:CGRectMake(8 , 4, 45, 45)];
    [self.selectedBt setImage:[UIImage imageNamed:@"未选中"] forState:(UIControlStateNormal)];
    [self.selectedBt setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateSelected];
    [self.selectedBt setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateHighlighted];
    [self.selectedBt addTarget:self action:@selector(selectedBt:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:_selectedBt];
    
    UILabel *allselectLabel  =[[UILabel alloc]initWithFrame:CGRectMake(55, 10, 80, 30)];
    allselectLabel.text  = [UtilCheck language:@"delivery.bottom7"];
    allselectLabel.textColor = [UtilCheck hexStringToColor:@"555555" alpha:1];
    [bottomView addSubview:allselectLabel];

    
    bottomView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:bottomView];
    
}
#pragma mark 下一步
- (void)nextAction:(UIButton *)bt{

    if (self.detailMutableArr.count<1) {
        [[BDHUD sharedManager]showWords:[UtilCheck language:@"pickVC.addPartTishi"]];
        return;
    }
    // 客服直接取件
    if ([bt.titleLabel.text isEqualToString:@"确认取件"]) {
        NSDictionary *dic1 = @{@"type":@"2",@"code":pickserialnumber,@"parts":self.detailMutableArr};
        [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
        [AFHttpTool postJsonDatawithUrl:@"cconfirmPick" parameters:dic1 success:^(id responseObject) {
            if ([[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] == 1) {
                // 取件成功显示这层
                [self showZhenceng];
                //            MainVC *vc= [[MainVC alloc]init];
                //            [self.navigationController pushViewController:vc animated:YES];
            }else {
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        } fail:^(id responseObject, NSError *error) {
            [[BDHUD sharedManager] dismissHUD];
            
            if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
            }else {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
            }
        }];
    }
    else{
        CunjianDetailVC *vc = [[CunjianDetailVC alloc]init];
        vc.serialNumber = pickserialnumber;
        vc.isQujian = @"1";
        vc.cabinetCode = [[self.detailMutableArr firstObject]objectForKey:@"cargoSpace"];
        vc.partArr = self.detailMutableArr;
        vc.isFaultypiece = self.type;
        vc.number = allCount;
        vc.titlename = [UtilCheck language:@"order.qudetail"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

// 取件件成功提示遮层
- (void)showZhenceng{
    //1. 取出window
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //2. 创建背景视图
    bagview = [[UIView alloc]init];
    bagview.frame = window.bounds;
    //3. 背景颜色可以用多种方法
    bagview.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
    [window addSubview:bagview];
    //4. 把需要展示的控件添加上去
    feedabackView = [[NSBundle mainBundle]loadNibNamed:@"OperationtipsView" owner:self options:nil].firstObject;
    feedabackView.layer.cornerRadius = 7;
    feedabackView.layer.masksToBounds = YES;
    [feedabackView.knowButton setTitle:[UtilCheck language:@"show.gotIt"] forState:UIControlStateNormal];
    [feedabackView.knowButton addTarget:self action:@selector(hideAlertView) forControlEvents:UIControlEventTouchUpInside];
    [bagview addSubview:feedabackView];
    feedabackView.isCun = @"1";
    //5. 动画简单(low)
    [UIView animateWithDuration:0.15 animations:^{
        NSInteger orangey = 100 ;
        feedabackView.frame = CGRectMake((self.view.frame.size.width-280)/2, orangey, 280, 220);
    }];
    //6.给背景添加一个手势，后续方便移除视图
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideAlertView)];
    [bagview addGestureRecognizer:tap];
}
- (void)hideAlertView{
    //动画简单(low)
    [UIView animateWithDuration:0.3 animations:^{
        feedabackView.frame = CGRectMake(0, SCREEN_HEIGHT, 280, 180);
    }];
    // 延迟几秒移除视图
    [self performSelector:@selector(remove) withObject:nil afterDelay:0.3];
}
- (void)remove{
    [bagview removeFromSuperview];
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.shouldChangeOrientation = NO;
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    CunquHomeVC *vc = [[CunquHomeVC alloc]init];
    vc.cabinetCode = self.quCabinetCode;
    [self.navigationController pushViewController:vc animated:YES];
}
// 全选
- (void)selectedBt:(UIButton *)bt{
    bt.selected = !bt.selected;
    isAll = !isAll;
    allCount = 0;
    UILabel *coutLabel = (UILabel *)[self.view viewWithTag:1001];
    coutLabel.text  = bt.selected ? [NSString stringWithFormat:[UtilCheck language:@"setting.tallCount"],(int)dataArr.count] : [UtilCheck language:@"delivery.bottom8"];
    if (bt.selected==NO) {
        [self.detailMutableArr removeAllObjects];
        [alreadySeletMuArr removeAllObjects];
        for (int j=0; j<_allMutableArr.count; j++) {
            [alreadySeletMuArr addObject:@"0"];
        }
    }
    [_tableView reloadData];
}
    
#pragma mark -已收货报告,处理方法
//开始时间
- (void)startBut {
    tag = startBut.tag;
    [self selectionTime];
}
//结束时间
- (void)endBut {
    tag = endBut.tag;
    [self selectionTime];
}
//时间选择器
- (void)selectionTime {
    UIView *maskView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.height, self.view.width)];
    maskView.backgroundColor = [UIColor whiteColor];
    maskView.alpha = 0.2f;
    self.maskView = maskView;
    [self.view addSubview:self.maskView];
    
    //设置选择时间的TextField
    datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 216, self.view.frame.size.width, 216)];
    datePicker.backgroundColor = [UIColor whiteColor];
    datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:[UtilCheck language:@"datePicker.LocalID"]];
    
    toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 216 - 44, self.view.frame.size.width, 44.0f)];
    toolBar.backgroundColor = [UIColor grayColor];
    UIBarButtonItem* leftItem = [[UIBarButtonItem alloc] initWithTitle:[UtilCheck language:@"button.cancel"] style:UIBarButtonItemStyleDone target:self action:@selector(cancelAction)];
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithTitle:[UtilCheck language:@"button.done"] style:UIBarButtonItemStyleDone target:self action:@selector(confirmAction:)];
    [toolBar setItems:@[leftItem,flexSpace,rightItem]];
    [self.view addSubview:datePicker];
    [self.view addSubview:toolBar];
}
- (void)cancelAction {
    [self.maskView removeFromSuperview];
    [datePicker removeFromSuperview];
    [toolBar removeFromSuperview];
}
- (void)confirmAction:(UIBarButtonItem *)item {
    [self.maskView removeFromSuperview];
    [datePicker removeFromSuperview];
    [toolBar removeFromSuperview];
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    //选择时间不能大于当前时间
    NSDate *selectedDate = datePicker.date;
    NSDate *nowDate = [NSDate date];
    if ([selectedDate earlierDate:nowDate] == selectedDate ) {
        [Toolobject showTextWithMessage:[UtilCheck language:@"datePicker.noBeforeNow"]]; //@"选择的时间不能早于当前时间"
        return;
    }
    if (tag == 101) {
        [startBut setTitle:[formatter stringFromDate:datePicker.date] forState:(UIControlStateNormal)];
        [_stockStrDict setValue:[formatter stringFromDate:datePicker.date] forKey:@"startTime"];
    }else {
        [endBut setTitle:[formatter stringFromDate:datePicker.date] forState:(UIControlStateNormal)];
        [_stockStrDict setValue:[formatter stringFromDate:datePicker.date] forKey:@"endTime"];
    }
    
}
//输入框处理
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([textField.text isEqualToString:@" "]) {
    }else {
        if (textField.tag == 201) {
            [_stockStrDict setValue:textField.text forKey:@"custName"];
        }else {
            [_stockStrDict setValue:textField.text forKey:@"searchKey"];
        }
//        [self shipmentReport];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    //禁用侧滑手势方法
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self horizontalscreensetting];
    
}


#pragma mark popView弹出

- (void)changeSearchType:(UIButton *)btn
{
    _coverView = [[UIView alloc]initWithFrame:self.view.frame];
    [_coverView setBackgroundColor:[THMangerTool getRZColor:250 green:250 blue:250 alpha:0.1]];
    [self.view addSubview:_coverView];
    if (!showPop) {
        
        StockPopVIewController *popView = [[StockPopVIewController alloc]init];
        popView.teger = @"1";
        popView.delegate = self;
        [popView.view setFrame:CGRectMake(50, CGRectGetMaxY(btn.frame), 180, 142)];
        [_coverView addSubview:popView.view];
        _popView = popView;
        showPop = YES;
    }
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchBar);
//    self.searchKey = searchBar.text;
    if ([searchText isEqualToString:@""]) {
        self.postDict[@"searchKey"] = searchText;
        [self InquiryInventory];
    }
}

- (void)warehouseSearch:(UIButton *)btn {
    _coverView = [[UIView alloc]initWithFrame:self.view.frame];
    [_coverView setBackgroundColor:[THMangerTool getRZColor:250 green:250 blue:250 alpha:0.1]];
    [self.view addSubview:_coverView];
    if (!showPop) {
        StockPopVIewController *popView = [[StockPopVIewController alloc]init];
        popView.delegate = self;
        popView.popViewArr = stockArr;
        [popView.view setFrame:CGRectMake(150, CGRectGetMaxY(btn.frame), 180, 222)];
        [_coverView addSubview:popView.view];
        _popView = popView;
        showPop = YES;
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (teger == 1) {
        [self.view endEditing:YES];
        teger = 0 ;
    }else {
        if (showPop == YES) {
            [_coverView removeFromSuperview];
            [_popView.view removeFromSuperview];
            [_popView removeFromParentViewController];
            showPop = NO;
        }
    }
}
//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    teger = 1;
    
}

- (void)didSelectPopCell:(NSInteger)row
{
    [_coverView removeFromSuperview];
    type = row+1;
    [_popView.view removeFromSuperview];
    _popView = nil;
    showPop = NO;
    self.postDict[@"searchKey"] = self.searchBar.text;
    switch (type) {
        case searchTypeFixpart:
            [_typeBtn setTitle:[UtilCheck language:@"order.search.fix"]  forState:UIControlStateNormal];
            [self InquiryInventory];
            break;
        case searchTypeAll:
            [_typeBtn setTitle:[UtilCheck language:@"order.search.all"] forState:UIControlStateNormal];
            [self InquiryInventory];
            
            break;
        case searchTypeFaultpart:
            [_typeBtn setTitle:[UtilCheck language:@"order.search.fault"] forState:UIControlStateNormal];
            [self InquiryInventory];
            
            break;
        default:
            break;
    }
}
- (void)didSelectPopCellTwo:(NSInteger)row setArr:(NSMutableArray *)arr{
    
    [_coverView removeFromSuperview];
    type = row+1;
    [_popView.view removeFromSuperview];
    _popView = nil;
    showPop = NO;
    self.postDict[@"storeName"] = stockArr[row];
    if (type == 1) {
        self.postDict[@"type"] = [NSString stringWithFormat:@"%d",type];
        self.postDict[@"storeName"] = arr[row];
        [_storeNameBtn setTitle:arr[row] forState:(UIControlStateNormal)];
    }
    else
    {
        self.postDict[@"type"] = [NSString stringWithFormat:@"%d",type-1];
        self.postDict[@"storeName"] = arr[row];
        [_storeNameBtn setTitle:arr[row] forState:(UIControlStateNormal)];
    }
    [self InquiryInventory];
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.postDict[@"searchKey"] = searchBar.text;
    
//    if (type == 1) {
//        self.postDict[@"type"] = [NSString stringWithFormat:@"%d",type];
//        self.postDict[@"searchKey"] = searchBar.text;
//    }
//    else
//    {
//        self.postDict[@"type"] = [NSString stringWithFormat:@"%d",type-1];
//        self.postDict[@"searchKey"] = searchBar.text;
//    }
    [self InquiryInventory];
}

- (void)backView
{
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.shouldChangeOrientation = NO;
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_searchBar resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    //禁用侧滑手势方法
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self setShupingAction];
}
   
// 设置竖屏
- (void)setShupingAction{
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.shouldChangeOrientation = NO;
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}


#pragma mark- UITableViewDelegate / DataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    settleDeliveryUpCell *cell = (settleDeliveryUpCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    if ([_stockStr isEqualToString:@"1"]) {
        ShipmentReportCell *cell = (ShipmentReportCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.textColor = [UIColor blackColor];
        return cell.cellHeight;
    }else {
        PickHeaderCell *cell = (PickHeaderCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.cellHeight;
    }
    
}
//调整
-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        //删除
        [dataArr removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    StockInquiryCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    PlateModel *plate = dataArr[indexPath.row];
//    StockInquryDetailVC *detailVC = [[StockInquryDetailVC alloc] init];
//    detailVC.plate = plate;
//    detailVC.title = [UtilCheck language:@"setting.stockInquiry"];
//    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detailVC];
//    AppDelegate * app = [UIApplication sharedApplication].delegate;
//    app.shouldChangeOrientation = NO;
//    [self presentViewController:nav animated:YES completion:nil];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_stockStr isEqualToString:@"1"]) {
        ShipmentReportCell *cell = [[ShipmentReportCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ShipmentReportCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.plateModel = dataArr[indexPath.row];
        [cell setPlateModel:dataArr[indexPath.row]];
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(10,cell.cellHeight - 0.5f, SCREEN_WIDTH - 20, 0.5f)];
        line.backgroundColor = [UtilCheck hexStringToColor:@"EcEcEc" alpha:1];
        [cell.contentView addSubview:line];
        return cell;
    }else {
        PickHeaderCell *cell = [[PickHeaderCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"PickHeaderCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.plateModel = dataArr[indexPath.row];
        [cell setPlateModel:dataArr[indexPath.row]];
        cell.alreadystatus = alreadySeletMuArr[indexPath.row];
        cell.isall = isAll;
        if ([coutmutableDic objectForKey:[NSString stringWithFormat:@"板件%d",(int)indexPath.row]]!=nil) {
            cell.numForAlready = [[coutmutableDic objectForKey:[NSString stringWithFormat:@"板件%d",(int)indexPath.row]]intValue];
        }
        else{
            cell.numForAlready = 1;
        }
        // 选中的数量
        cell.countBlock = ^(NSInteger count,NSInteger sub) {
            [coutmutableDic setObject:[NSString stringWithFormat:@"%d",(int)count] forKey:[NSString stringWithFormat:@"板件%d",(int)indexPath.row]];
            NSMutableDictionary *selecdic = self.allMutableArr[indexPath.row];
            [selecdic setObject:[NSString stringWithFormat:@"%d",(int)count] forKey:@"number"];
            if ([self.detailMutableArr containsObject:selecdic]) {
                [self.detailMutableArr removeObject:selecdic];
            }
            [alreadySeletMuArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
            [self.detailMutableArr addObject:selecdic];
            UILabel *coutLabel = (UILabel *)[self.view viewWithTag:1001];
            if (sub==-1) {
                allCount = allCount - count;
                [self.detailMutableArr removeObject:selecdic];
                coutLabel.text  =[NSString stringWithFormat:@"合计 : %d件",(int)allCount];
                [alreadySeletMuArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
                return ;
            }
            if (sub==-2) {
                allCount = allCount + count;
                coutLabel.text  =[NSString stringWithFormat:@"合计 : %d件",(int)allCount];
//                [alreadySeletMuArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
                return ;
            }
            allCount = sub==1 ? allCount + 1 : allCount - 1;
            coutLabel.text  =[NSString stringWithFormat:@"合计 : %d件",(int)allCount];
//            coutLabel.text  = [UtilCheck language:@"合计 : 0件"];
        };
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(10,cell.cellHeight - 0.5f, SCREEN_WIDTH - 20, 0.5f)];
        line.backgroundColor = [UtilCheck hexStringToColor:@"EcEcEc" alpha:1];
        [cell.contentView addSubview:line];
        return cell;
    }
}

#pragma mark
#pragma mark- 取件流水号
- (void)pickserialnumber{

    NSString *key = [THMangerTool getKey];
    [AFHttpTool postJsonDatawithUrl:@"getRetrieveSerialNumber"  parameters:@{@"key":key} success:^(id responseObject) {
        NSLog(@"responseobject ----- %@",responseObject);
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
            pickserialnumber = [responseObject objectForKey:@"data"][@"serialNumber"]; // 流水号
        }
    } fail:^(id responseObject, NSError *error) {
        NSLog(@"%@",error);
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
}

#pragma mark 网络请求--可取件查询
- (void)InquiryInventory {
    //    self.postDict[@"storeName"] = @"北京SPM库";
//    self.postDict[@"type"] = [NSString stringWithFormat:@"%d",type];
//    NSLog(@"postdic ==== %@",self.postDict);
    
    if ([self.postDict objectForKey:@"searchKey"]==nil) {
         [self.postDict setObject:@"" forKey:@"searchKey"];
    }
    if (self.quCabinetCode==nil) {
      NSString *cabinetCode = [[NSUserDefaults standardUserDefaults]objectForKey:@"cabinetCode"];
        [self.postDict setObject:cabinetCode forKey:@"cabinetCode"];
    }
    else{
        [self.postDict setObject:self.quCabinetCode forKey:@"cabinetCode"];
    }
    [self.postDict setObject:self.type forKey:@"type"];
    [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
    [AFHttpTool postJsonDatawithUrl:@"getDesirableList"  parameters:self.postDict success:^(id responseObject) {
        NSLog(@"responseobject ----- %@",responseObject);
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
            NSArray *arr = [responseObject objectForKey:@"data"][@"parts"];
            [self.allMutableArr addObjectsFromArray:arr];
            if (arr.count > 0) {
                // 用于存储选择按钮的状态
                for (int i=0; i<arr.count; i++) {
                    [alreadySeletMuArr addObject:@"0"];
                }
                [dataArr removeAllObjects];
                dataArr = [self modelWithDic:arr];
                self.tableView.tableHeaderView = self.headView;
                number = responseObject[@"data"][@"total"];
                NSString *countStr2 = [NSString stringWithFormat:[UtilCheck language:@"setting.plateCount"],number];
                self.headView.titleLab.attributedText = [self attributedString:countStr2];
                
                [_searchBar resignFirstResponder];
                [self.tableView reloadData];
            }
            else {
                [dataArr removeAllObjects];
                [self.tableView reloadData];
                self.tableView.tableHeaderView = nil;
                [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView  top:30 title:[THMangerTool language:@"HUD.noData"]  onClick:nil];
            }
        }
        else {
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        NSLog(@"%@",error);
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
}

- (NSMutableArray *)modelWithDic:(NSArray *)arr
{
    NSMutableArray *muArr = [NSMutableArray array];
    for (int i = 0 ; i < arr.count; i ++) {
        NSMutableDictionary *dic = arr[i];
        dic[@"number"] = [NSString stringWithFormat:@"%@",dic[@"number"]];
//        PlateModel *plate = [[PlateModel alloc]init];
        PickupModel *pickupmodel = [[PickupModel alloc]init];
        //        plate.warehouse = @"xx库房";
        [pickupmodel setValuesForKeysWithDictionary:dic];
        [muArr addObject:pickupmodel];
    }
    return muArr;
}

- (void)touchSearchBtn:(UIButton *)sender {
    // self.searchHoldView.hidden= YES;
}

#pragma mark- 其他事件
#pragma mark-

/**
 *  更改字符串的前两个空格之间字符串的颜色
 *
 *  @param txt 要改变颜色的字符床
 1231
 *
 *  @return 改变后的字符串
 */
- (NSMutableAttributedString *)attributedString:(NSString *)txt {
    
    // 查找出前两个空格的位置
    NSInteger start = 0;
    NSInteger end = 0;
    NSRange countRange = NSMakeRange(0, 0);
    
    for (int i = 0 ; i < txt.length; i ++) {
        if ([txt characterAtIndex:i] == 32 && start == 0) {
            start = i;
            
        }
        else if([txt characterAtIndex:i] == 32){
            end = i;
            countRange = NSMakeRange(start + 1, end - start);
            break;
        }
    }
    // 改变范围内字符颜色
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:txt];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UtilCheck hexStringToColor:@"40BFF5" alpha:1] range:countRange];
    
    return attributeStr;
}



@end
